package com.monitor.handler;

import com.monitor.entity.response.Rs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


/**
 * 自定义全局异常.
 *
 * @author Li Zhiyuan
 * @since 2020-11-16
 */
@ControllerAdvice
@Slf4j
public class AllExceptionHandler {

    //传入参数为空异常处理
    @ResponseStatus(value = HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Rs handleBusinessException(MethodArgumentNotValidException e) {
        log.info(e.getMessage(), e);
        StringBuilder messages = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(l -> messages.append("[").append(l.getField()).append(":").append(l.getDefaultMessage()).append("]"));
        Rs rs = new Rs();
        rs.setCode(400);
//        rs.setMessage(e.getBindingResult().getFieldError().getDefaultMessage());
        rs.setMessage(messages.toString());
        return rs;
    }
}
